package cn.android666.mediacodecasynchronous

import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.opengl.GLES11Ext
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import cn.android666.mediacodecasynchronous.permission.PermissionUtil
import timber.log.Timber

class MainActivity : AppCompatActivity() {

    private var camera: Camera? = null
    private var h264Encoder: H264Encoder? = null
    private val surfaceTexture: SurfaceTexture by lazy { SurfaceTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES) }
    private val videoWidth = 640
    private val videoHeight = 480

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        PermissionUtil.registerForActivityResult(this)

        val openCameraButton: Button = findViewById(R.id.openCameraButton)
        val closeCameraButton: Button = findViewById(R.id.closeCameraButton)

        openCameraButton.setOnClickListener {
            PermissionUtil.requestPermission(this) {
                Timber.i("得到所有的权限了")
                openCamera()
            }
        }

        closeCameraButton.setOnClickListener { closeCamera() }

    }

    private fun openCamera() {
        if (camera != null) {
            return
        }

        h264Encoder = H264Encoder(videoWidth, videoHeight)
        camera = Camera.open()
        camera?.parameters = camera?.parameters?.apply {
            setPreviewSize(videoWidth, videoHeight)
            setPictureSize(videoWidth, videoHeight)
            previewFormat = ImageFormat.NV21
            previewFrameRate = 25
            focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
        }
        camera?.setPreviewTexture(surfaceTexture)
        camera?.setPreviewCallback { data, _ ->
            h264Encoder?.addYUVBytes(data)
        }
        camera?.startPreview()
    }

    private fun closeCamera() {
        camera?.setPreviewCallback(null)
        camera?.stopPreview()
        camera?.release()
        camera = null
        h264Encoder?.close()
        h264Encoder = null
    }

    override fun onDestroy() {
        super.onDestroy()
        closeCamera()
    }
}